package com.woniu.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.woniu.admin.vo.AjaxResult;
import com.woniu.common.constants.Constants;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class UploadController {

    @PostMapping("/upload")
    public AjaxResult upload1(@RequestParam("file") MultipartFile file) throws IOException {
        //1,准备存储文件的目录
        String today = DateUtil.format(DateUtil.date(), Constants.DEFAULT_CHINA_DATE_FORMAT);

        // D://java//nginx-1.21.6//html//user_img//
        String fullPath = Constants.DEFAULT_UPLOAD_IMAGE_PATH + today;
        //2,创建目录
        FileUtil.mkdir(fullPath);

        //2,文件重命名
        String uuid = IdUtil.randomUUID().toUpperCase().replace("-", "");

        String originalFilename = file.getOriginalFilename();
        //
        String newFilename = uuid + Constants.DEFAULT_IMAGE_FILE_SEPARATOR + originalFilename;
        //3,文件上传
        file.transferTo(new File(fullPath + "/" + newFilename));
        //4,返回访问地址 http://image.wncinema.com/today/newFilename
        return AjaxResult.success("上传成功", Constants.DEFAULT_BASE_VISIT_IMAGE_URL + today + "/" + newFilename);
    }
}
